# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: yuxuan

import json
import os
import tabulate

from coin_deploy.basis_strat.strat_list import PROD_STRATS
from coin_deploy.basis_strat2.strat_list import PROD_STRATS as PROD_STRATS2
from coin.strategy.basis_strat.analysis.utils import \
    get_strategy_config_from_script, get_reference_trade_futures_type


def output_summaries():
  pos_configs = []
  is_coin2 = [False] * len(PROD_STRATS) + [True] * len(PROD_STRATS2)
  for is_coin2, strat in zip(is_coin2, PROD_STRATS + PROD_STRATS2):
    if not is_coin2:
      script_name = strat['binary']
      configs, flags = get_strategy_config_from_script('coin_deploy', script_name)
      strategy_name = configs['common']['strategy_request']['strategy_name']
      if strategy_name.startswith('basis_spread'):
        continue
      strategy_group = configs['common']['strategy_request']['strategy_group']
      exch0_subreq = configs['common']['exch0_subreq']
      exch1_subreq = configs['common']['exch1_subreq']
      fut_type0, fut_type1 = get_reference_trade_futures_type(configs)
      ref0 = '%s,%s,%s' % (
          exch0_subreq['exchange'], fut_type0, exch0_subreq.get('api_version', None))
      ref1 = '%s,%s,%s' % (
          exch1_subreq['exchange'], fut_type1, exch1_subreq.get('api_version', None))

      print('%s,%s' % (strategy_group, strategy_name))
      print('  ref: %s' % ref0)
      print('  trade: %s' % ref1)
      print('  flags:')
      for key in sorted(flags.keys()):
        print('    --%s=%s' % (key, flags[key]))
      print('\n')

      for key, cfg in configs['products1'].items():
        run_size = float(flags.get('run_size', 1.0))
        min_pos = cfg['min_pos']
        max_pos = cfg['max_pos']
        lot_size = cfg['lot_size'] * run_size
        neutral_pos = (max_pos + min_pos) / 2.0
        pos_range = max_pos - min_pos
        min_pos = neutral_pos - pos_range / 2.0 * run_size
        max_pos = neutral_pos + pos_range / 2.0 * run_size
        pos_configs.append(
            [strategy_group, strategy_name, ref0, ref1, key, min_pos, max_pos, lot_size])
    else:
      config_path = os.path.join('coin_deploy/basis_strat2/config/%s.json' % strat['name'])
      driver_path = os.path.join('coin_deploy/basis_strat2/driver/%s.json' % strat['name'])
      with open(config_path) as fi:
        configs = json.load(fi)
      with open(driver_path) as fi:
        driver = json.load(fi)
      recipe0 = driver['feed']['reference']['recipe']
      recipe1 = driver['feed']['trade']['recipe']
      strategy_group = strat['group']
      strategy_name = strat['name']
      for product, cfg in configs['products'].items():
        ref0 = '%s.%s' % (cfg['ref_symbol'].split(':', 1)[-1], recipe0)
        ref1 = '%s.%s' % (cfg['trade_symbol'].split(':', 1)[-1], recipe1)
        key = ref1
        min_pos = cfg['min_pos']
        max_pos = cfg['max_pos']
        lot_size = cfg['lot_size']
        pos_configs.append(
            [strategy_group, strategy_name, ref0, ref1, key, min_pos, max_pos, lot_size])

  for config in pos_configs:
    if config[0].startswith('basis'):
      config[0] = config[0].split('_', 1)[-1]
    if config[1].startswith('basis'):
      config[1] = config[1].split('_', 1)[-1]
    config.append((config[-2] - config[-3]) / config[-1])

  config_str = tabulate.tabulate(pos_configs,
                                 headers=[
                                     'strategy_group',
                                     'strategy_name',
                                     'reference',
                                     'trade',
                                     'symbol',
                                     'min_pos',
                                     'max_pos',
                                     'lot_size',
                                     'stack'
                                 ],
                                 tablefmt='grid')
  print(config_str)


if __name__ == '__main__':
  output_summaries()
